package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.jrbdp.protocol.manager.ManagerAtomTaskResult;
import cc.rengu.jrbdp.protocol.manager.ManagerCommand;
import cc.rengu.jrbdp.protocol.manager.ManagerTaskResult;
import cc.rengu.redp.bizimpl.igas.vo.BasePage;
import cc.rengu.redp.bizimpl.upmp.bean.BatchTaskBean;
import cc.rengu.redp.bizimpl.upmp.service.BatchTaskService;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.RbdpClient;
import cc.rengu.redp.common.domain.RedpResponse;
import cc.rengu.utility.base.TimeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class BatchTaskServiceImpl implements BatchTaskService {

    private static final Logger logger = LoggerFactory.getLogger(BatchTaskServiceImpl.class);
    @Override
    public Map<String, Object> getTopTasks(HttpServletRequest request) {
        List<ManagerTaskResult> topTasks;
        String settleDate = request.getParameter("settleDate");
        if (null == settleDate || settleDate.isEmpty()) {
            settleDate = TimeUtil.getDateTime("yyyyMMdd");
        } else {
            settleDate = request.getParameter("settleDate").replace("-", "");
        }
        topTasks = RbdpClient.getIntance2().getTopTasks(settleDate);
        if (topTasks != null) {
            logger.info("顶级任务====:  {}", JSON.toJSONString(topTasks));
        } else {
            logger.error("获取顶级任务失败: {}",RbdpClient.getIntance2().getError());
        }
        List<BatchTaskBean> list = new ArrayList<BatchTaskBean>();
        try{
            for (ManagerTaskResult dao : topTasks) {
                BatchTaskBean btb = new BatchTaskBean();
                btb.setTopTask(dao.getTaskBatch() + "-" + dao.getTaskPath());
                btb.setTaskBatch(dao.getTaskBatch());
                btb.setTaskPath(dao.getTaskPath());
                btb.setSettleDate(dao.getSettleDate());
                btb.setTaskType(dao.getTaskType());
                btb.setTaskState(dao.getTaskState());
                btb.setStateDesc(dao.getStateDesc());
                btb.setTaskPrio(dao.getTaskPrio());
                list.add(btb);
            }
        }catch(Exception ex){
            logger.error("获取顶级任务失败",ex);
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("content", list);
        resultMap.put("page", 1);
        resultMap.put("totalElements", list.size());
        resultMap.put("totalPages", 1);
        System.out.println(resultMap);
        return resultMap;
    }

    @Override
    public RedpResponse addEntity(HttpServletRequest request) {
        RedpResponse redpResponse = new RedpResponse();
        String taskName = (String) request.getParameter("taskName").split("-")[0];
        String settleDate = ((String) request.getParameter("settleDate")).replace("-", "");
        String taskBatch = (String) request.getParameter("taskBatch");
        String taskParam = (String) request.getParameter("taskParam");
        String registerDate = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss");
        // 格式化后台的时间
//        String time = CommonUtils.getTime(registerDate).substring(8, 14);
        String time = registerDate.substring(8, 14);
        /*
         * if(registerDate.length() != 6){ return "false"; }
         */
        logger.info("注册任务请求参数：taskName = {}, settleDate = {}, taskBatch = {}, taskParam = {}, ",taskName,settleDate,taskBatch,taskParam);
        // ???????原来四个参数！！！！！！ //getAllTasks()
        int ret = RbdpClient.getIntance1().registerTask(taskName, settleDate, settleDate + time, taskBatch, taskParam);
        logger.info("实时任务注册返回：ret {}" , ret);
        String result = "";
        if (0 != ret) {
            result = "注册失败: " + RbdpClient.getIntance1().getError();
            return redpResponse.message(result).failure();
        } else
            result = "注册成功.";
        return redpResponse.message(result).success();
    }

    @Override
    public RedpResponse resumeTask(HttpServletRequest request) {
        String settleDate = request.getParameter("settleDate");
        String taskBatch = request.getParameter("taskBatch");
        String taskPath = request.getParameter("taskPath");
        String taskType = request.getParameter("taskType");
        boolean flag;
        if(taskType == null){
            ManagerTaskResult etk = new ManagerTaskResult();
            etk.setSettleDate(settleDate);
            etk.setTaskBatch(taskBatch);
            etk.setTaskPath(taskPath);
            flag = RbdpClient.getIntance2().manualHandleTask(ManagerCommand.RESUME_TASK, etk);
        }else{
            ManagerTaskResult rtk = new ManagerTaskResult();
            rtk.setSettleDate(settleDate);
            rtk.setTaskBatch(taskBatch);
            rtk.setTaskPath(taskPath);
            flag = RbdpClient.getIntance2().manualHandleTask(ManagerCommand.RESUME_TASK, rtk);
        }
        if(flag){
            return RedpResponse.getInstance().success().message("继续任务成功！");
        }
        return RedpResponse.getInstance().failure().message("继续任务失败！");
    }

    @Override
    public RedpResponse redoTask(HttpServletRequest request) {
        String settleDate = request.getParameter("settleDate");
        String taskBatch = request.getParameter("taskBatch");
        String taskPath = request.getParameter("taskPath");
        String taskAllPath = request.getParameter("taskAllPath");
        String taskType = request.getParameter("taskType");
        String redoFlag = request.getParameter("redoFlag");
        boolean flag;
        if(taskType == null){
            ManagerTaskResult etk = new ManagerTaskResult();
            etk.setSettleDate(settleDate);
            etk.setTaskBatch(taskBatch);
            etk.setTaskPath(taskAllPath);
            if(redoFlag != null && !redoFlag.equals("") && redoFlag.equals("1")){
                flag = RbdpClient.getIntance2().manualHandleTask(ManagerCommand.REDO_DEPEND_TASK, etk);
            }else{
                flag = RbdpClient.getIntance2().manualHandleTask(ManagerCommand.REDO_TASK, etk);
            }
        }else{
            ManagerTaskResult rtk = new ManagerTaskResult();
            rtk.setSettleDate(settleDate);
            rtk.setTaskBatch(taskBatch);
            rtk.setTaskPath(taskAllPath);
            if(redoFlag != null && !redoFlag.equals("") && redoFlag.equals("1")){
                flag = RbdpClient.getIntance2().manualHandleTask(ManagerCommand.REDO_DEPEND_TASK, rtk);
            }else{
                flag = RbdpClient.getIntance2().manualHandleTask(ManagerCommand.REDO_TASK, rtk);
            }
        }
        if(flag){
            return RedpResponse.getInstance().success().message("重做任务成功！");
        }
        return RedpResponse.getInstance().failure().message("重做任务失败！");
    }

    @Override
    public Map<String, Object> getAtomInfo(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        String taskPath = request.getParameter("taskPath");
        String settleDate = request.getParameter("settleDate");
        String taskBatch = request.getParameter("taskBatch");
        String taskId = request.getParameter("taskId");
        logger.info("taskPath =[" + taskPath + "],settleDate=[" + settleDate + "],taskBatch=[" + taskBatch + "]");
        ManagerTaskResult atomTasks = RbdpClient.getIntance2().getTask(settleDate, taskBatch, taskPath);
        // .getTask(settleDate, taskBatch, taskPath, Integer.parseInt(taskId));
        String json = JSON.toJSONString(atomTasks);
        /**
         * BatchTaskBean btb = atomTasktoBean(atomTasks); Object jsonArray = JSONArray.toJSON(atomTasks); return
         * jsonArray;
         */
        logger.info("json = [" + json + "]");
        resultMap.put("taskPath",taskPath);
        resultMap.put("settleDate",settleDate);
        resultMap.put("taskBatch",taskBatch);
        resultMap.put("taskId",taskId);
        resultMap.put("content",json);
        return resultMap;
    }

    @Override
    public Object findSubTasks(HttpServletRequest request) {
        String settleDate = request.getParameter("settleDate");
        String taskBatch = request.getParameter("taskBatch");
        String taskPath = request.getParameter("taskPath");
        String taskType = request.getParameter("taskType");
        //String taskType = "0";
        String taskState = request.getParameter("taskState");

        ManagerTaskResult rtk = new ManagerTaskResult();
        rtk.setSettleDate(settleDate);
        rtk.setTaskBatch(taskBatch);
        rtk.setTaskPath(taskPath);

        List strList = new ArrayList();
        if(taskType != null && taskType.equals("2")){
            List<ManagerAtomTaskResult> atomTasks = RbdpClient.getIntance2().getAtomTasks(rtk);
            for(ManagerAtomTaskResult map : atomTasks){
                BatchTaskBean btb = new BatchTaskBean();
//				btb.setTaskId(map.getTaskId());
                btb.setRegTime(rtk.getRegTime());
                btb.setSettleDate(rtk.getSettleDate());
                btb.setTaskBatch(rtk.getTaskBatch());
                btb.setTaskDesc(rtk.getTaskDesc());
                String[] strTaskPath = rtk.getTaskPath().split("/");
                logger.debug("path.length = " + strTaskPath.length);
//				btb.setRealPath(strTaskPath[strTaskPath.length-1]);
                btb.setRealPath(rtk.getTaskPath());
//				btb.setRealPath(map.getTaskPath());初始:IN 成功：OK 失败：BF 运行中：others
                btb.setTaskPath(rtk.getTaskPath());
//				btb.setTaskPath(map.getTaskPath());
                btb.setTopNodeName(taskPath);
                btb.setTaskState(map.getTaskState());
                btb.setTopNodeState(taskState);
                btb.setStateDesc(map.getStateDesc());
                strList.add(btb);
            }
            logger.debug("size = " + strList.size());
        }else{
            List<ManagerTaskResult> subTasks = RbdpClient.getIntance2().getSubTasks(rtk);
            for(ManagerTaskResult map : subTasks){
                BatchTaskBean btb = new BatchTaskBean();
                btb.setParentPath(map.getParentPath());
                btb.setRegTime(map.getRegTime());
                btb.setSettleDate(map.getSettleDate());
                btb.setTaskBatch(map.getTaskBatch());
                btb.setTaskDesc(map.getTaskDesc());
                btb.setTaskType(map.getTaskType());
                String[] strTaskPath = map.getTaskPath().split("/");
                btb.setRealPath(strTaskPath[strTaskPath.length-1]);
//				btb.setRealPath(map.getTaskPath());
                btb.setTaskPath(map.getTaskPath());
                btb.setTopNodeName(taskPath);
                btb.setTaskState(map.getTaskState());
                btb.setTopNodeState(taskState);
                btb.setTopNodeSettleDate(settleDate);
                btb.setTopNodeTaskBatch(taskBatch);
                btb.setStateDesc(map.getStateDesc());
                btb.setTaskId(map.getTaskPrio());
                strList.add(btb);
            }
        }


        Object jsonArray = JSONArray.toJSON(strList);
        return jsonArray;
    }

    public void getSubTasks(Map<String,String> objMap,List strList) throws Exception {
        ManagerTaskResult rtk = new ManagerTaskResult();
        rtk.setSettleDate(objMap.get("settleDate"));
        rtk.setTaskBatch(objMap.get("taskBatch"));
        rtk.setTaskPath(objMap.get("nodeName"));
        String taskType = objMap.get("taskType");
        if(taskType != null && taskType.equals("2")){
            List<ManagerTaskResult> atomTasks = RbdpClient.getIntance2().getSubTasks(rtk);
            logger.info("batch = ["+objMap.get("nodeName")+"],atomTasks.size = [" + atomTasks.size() + "]");
            for (ManagerTaskResult exeTaskDao : atomTasks) {
                BatchTaskBean node = atomTasktoBean(exeTaskDao);
                node.setSuperNodeName(objMap.get("nodeName"));
                node.setNodeName(exeTaskDao.getTaskPath());
                strList.add(node);
            }
        }else{
            List<ManagerTaskResult> subTasks = RbdpClient.getIntance2().getSubTasks(rtk);
            logger.info("batch = ["+objMap.get("nodeName")+"],subTasks.size = [" + subTasks.size() + "]");
            for (ManagerTaskResult regTaskDao : subTasks) {
                Map map = new java.util.HashMap();
                map.put("settleDate", regTaskDao.getSettleDate());
                map.put("taskBatch", regTaskDao.getTaskBatch());
                map.put("nodeName", regTaskDao.getTaskPath());
                map.put("taskType", regTaskDao.getTaskType());
                map.put("taskState", regTaskDao.getTaskState());
                BatchTaskBean node = toBean(regTaskDao);
                node.setSuperNodeName(objMap.get("nodeName"));
                node.setNodeName(regTaskDao.getTaskPath());
                strList.add(node);
                getSubTasks(map, strList);
            }
        }
    }

    private BatchTaskBean atomTasktoBean(ManagerTaskResult atomTasks) {
        BatchTaskBean btb = new BatchTaskBean();
        btb.setSettleDate(atomTasks.getSettleDate());
        btb.setTaskBatch(atomTasks.getTaskBatch());
        btb.setTaskPath(atomTasks.getTaskPath());
//			btb.setTaskId(atomTasks.getTaskId());
        btb.setTaskPrio(atomTasks.getTaskPrio());
        btb.setTaskParam(atomTasks.getTaskParam());
        btb.setTaskDesc(atomTasks.getTaskDesc());
        btb.setExecutorName(atomTasks.getExecutorName());
//			btb.setSplitConfig(atomTasks.getSplitConfig());
//			btb.setBizConfig(atomTasks.getBizConfig());
//			btb.setDataFile(atomTasks.getDataFile());
        btb.setRegTime(atomTasks.getRegTime());
        btb.setExeMachName(atomTasks.getRegMachName());
        btb.setExeLogKey(atomTasks.getRegLogKey());
        btb.setStartTime(atomTasks.getTimeRange());
        btb.setFinishTime(atomTasks.getTimeRange());
        btb.setTaskState(atomTasks.getTaskState());
        btb.setStateDesc(atomTasks.getStateDesc());
        btb.setUpdateTime(atomTasks.getUpdateTime());
        return btb;
    }

    private BatchTaskBean toBean(ManagerTaskResult subTasks) {
        BatchTaskBean btb = new BatchTaskBean();
        btb.setSettleDate(subTasks.getSettleDate());
        btb.setTaskBatch(subTasks.getTaskBatch());
        btb.setTaskPath(subTasks.getTaskPath());
        btb.setParentPath(subTasks.getParentPath());
        btb.setPreTask(subTasks.getPreTask());
        btb.setTaskType(subTasks.getTaskType());
        btb.setTaskPrio(subTasks.getTaskPrio());
        btb.setTaskParam(subTasks.getTaskParam());
        btb.setTaskDesc(subTasks.getTaskDesc());
        btb.setExecutorName(subTasks.getExecutorName());
//			btb.setSplitConfig(subTasks.getSplitConfig());
//			btb.setBizConfig(subTasks.getBizConfig());
        btb.setRedoMTIV(subTasks.getRedoMTIV());
        btb.setTimeRange(subTasks.getTimeRange());
        btb.setRegMachName(subTasks.getRegMachName());
        btb.setRegLogKey(subTasks.getRegLogKey());
        btb.setRegTime(subTasks.getRegTime());
        btb.setTigMachName(subTasks.getTigMachName());
        btb.setTigLogKey(subTasks.getTigLogKey());
        btb.setTigTime(subTasks.getTigTime());
        btb.setTaskState(subTasks.getTaskState());
        btb.setStateDesc(subTasks.getStateDesc());
        btb.setInsertTime(subTasks.getInsertTime());
        btb.setUpdateTime(subTasks.getUpdateTime());
        return btb;
    }

    @Override
    public String pauseTask(HttpServletRequest request) {
        String settleDate = request.getParameter("settleDate");
        String taskBatch = request.getParameter("taskBatch");
        String taskPath = request.getParameter("taskPath");
        String taskType = request.getParameter("taskType");
        boolean flag;
        if (taskType == null) {
            ManagerTaskResult etk = new ManagerTaskResult();
            etk.setSettleDate(settleDate);
            etk.setTaskBatch(taskBatch);
            etk.setTaskPath(taskPath);
            flag = RbdpClient.getIntance2().manualHandleTask(ManagerCommand.PAUSE_TASK, etk);
        } else {
            ManagerTaskResult rtk = new ManagerTaskResult();
            rtk.setSettleDate(settleDate);
            rtk.setTaskBatch(taskBatch);
            rtk.setTaskPath(taskPath);
            flag = RbdpClient.getIntance2().manualHandleTask(ManagerCommand.PAUSE_TASK, rtk);
        }
        if (flag) {
            return "暂停任务成功！";
        }
        return "暂停任务失败！";
    }

    @Override
    public BasePage getTimingTasks(HttpServletRequest request) throws Exception {
        List<ManagerTaskResult> timiTasks = RbdpClient.getIntance2().getTimingTasks();
        List<BatchTaskBean> list = new ArrayList<BatchTaskBean>();
        try{
            for (ManagerTaskResult dao : timiTasks) {
                BatchTaskBean btb = new BatchTaskBean();
                btb.setTaskName(dao.getTaskPath());
                btb.setTaskBatch(dao.getTaskBatch());
                btb.setLastChkTime(dao.getLastChkTime());
                btb.setLastRegTime(dao.getLastRegTime());
                btb.setNextRegTime(dao.getNextRegTime());
                btb.setTaskDesc(dao.getTaskDesc());
                btb.setTaskParam(dao.getTaskParam());
                btb.setTaskPrio(dao.getTaskPrio());
                btb.setRedoMTIV(dao.getRedoMTIV());
                list.add(btb);
            }
        }catch(Exception ex){
            logger.error("查询定时任务失败",ex);
        }
        BasePage bp = new BasePage();
        bp.setContent(list);
        bp.setPage(1);
        bp.setTotalElements(list.size());
        bp.setTotalPages(1);
        return bp;
    }
}
